using BSDS.Core.Model;
using BSDS.Core.Model.Data;
using System;

namespace BSDS.Core.Data.Local.Csv.Parsing
{
    public class CsvAttributeInfoParser
    {
        //TODO: refactor 
        public AttributeInfo FromCsv(string value)
        {
            string name, datatype;
            bool isPrimaryKey;

            string[] parts = value.Split('(');
            name = parts[0];

            string typeInfo = parts[1].Substring(0, parts[1].Length - 1);

            if (!typeInfo.Contains("@") && !typeInfo.Contains(","))
            {
                datatype = typeInfo;
                isPrimaryKey = false;
            }
            else
            {
                if (typeInfo.Contains("@"))
                    datatype = typeInfo.Split('@')[0];
                else
                    datatype = typeInfo.Split(',')[0];
                isPrimaryKey = true;
            }

            datatype = datatype.Split('.')[1];

            return new AttributeInfo(name, ConvertDatatype(datatype), isPrimaryKey);
        }

        public AttributeInfo FromMultimapCSV(string value)
        {
            var trimmedValue = value.Trim(char.Parse("\""));

            // TODO: Hard-code this for now. Later, load mapping from a config file file
            switch (trimmedValue.ToLower())
            {
                case "id":           return new AttributeInfo("EntityID",      "String", true);
                case "lat":          return new AttributeInfo("Latitude",      "Double", false);
                case "lon":          return new AttributeInfo("Longitude",     "Double", false);
                case "addr1":
                case "street":       return new AttributeInfo("AddressLine",   "String", false); // Let data validation logic in BsdsDataValidator.cs check for duplicates
                case "addr3":
                case "town":         return new AttributeInfo("Locality",      "String", false);
                case "pc":           return new AttributeInfo("PostalCode",    "String", false);
                case "state":
                case "county":       return new AttributeInfo("AdminDistrict", "String", false);
                case "country":      return new AttributeInfo("CountryRegion", "String", false);
                default:             return new AttributeInfo(trimmedValue,    "String", false);
            }
        }

        public AttributeInfo FromMappointCSV(string value)
        {
            //TODO
            throw new NotImplementedException("Mappoint CSV auto-conversion is not yet supported.");
        }

        private static string ConvertDatatype(string datatype)
        {
            if (datatype.ToLower() == "int64")
            {
                return "long"; // See CsvFormatSerializer.ConvertDataType() which converts this back to Int64 upon re-serialization.
            }

            return datatype;
        }
    }
}